package cn.gson.crm.service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import cn.gson.crm.exception.UploadException;
import cn.gson.crm.model.dao.AttachmentDao;
import cn.gson.crm.model.entity.Attachment;

/**
 * 文件上传的服务
 * @author hzl
 * @date 2018年4月17日
 * @time 上午11:27:32
 */
@Service
public class UploadService {

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy" + File.separator + "MM");

	/**
	 * 允许上传的后缀
	 */
	private List<String> exts;

	private File root;

	@Autowired
	AttachmentDao attachmentDao;

	@Value("${upload.exts}")
	public void setExts(String exts) {

		this.exts = Arrays.asList(exts.split(","));
	}

	@Value("${upload.dir}")
	public void setRoot(String root) {
		File r = new File(root);
		if (!r.exists()) {
			// 如果目录部不存在就创建出来
			r.mkdirs();
		}
		this.root = r;
	}

	/**
	 * 保存文件
	 * 
	 * @param mf
	 * @return
	 */
	public Attachment save( MultipartFile mf) {
		// 判断文件是否允许保存，根据后缀判断
		// 文件的原始名称
		String orgName = mf.getOriginalFilename();
		// 获取文件后缀
		String ext = FilenameUtils.getExtension(orgName);
		String newFileName;
		String timePath = sdf.format(new Date());
		if (exts.contains(ext)) {
			// 生成新的文件名称
			newFileName = UUID.randomUUID().toString() + "." + ext;

			/// Users/gson/upload/2018/01/文件名称.xxx
			
			// 构建一个存储路径
			File savePath = new File(root, timePath);
			if (!savePath.exists()) {
				savePath.mkdirs();
			}
			// 存储文件
			try {
				mf.transferTo(new File(savePath, newFileName));

				// 构建一个Attachment对象
				Attachment att = new Attachment();
				att.setFileName(orgName);
				att.setSuffix(ext);
				att.setFileSize(mf.getSize());
				att.setContentType(mf.getContentType());
				att.setFilePath(timePath + "/" + newFileName);

				attachmentDao.save(att);

				return att;
			} catch (Exception e) {
				throw new UploadException("文件上传失败！", e);
			}
		} else {
			throw new UploadException(String.format("不支持[%s]此类型文件上传！", ext));
		}
	}

	public File get(String filePath) {
		File file = new File(root, filePath);
		if (!file.exists()) {
			throw new UploadException("[" + filePath + "]文件不存在！");
		}
		return file;
	}

	public void delete(String filePath) {
		File file = new File(root, filePath);

		if (!file.exists()) {
			throw new UploadException("[" + filePath + "]文件不存在！");
		}

		file.deleteOnExit();
	}
}
